<?php
namespace app\v1\controller;
use support\Request;
use app\model\BizModel;
use app\model\Util;
use app\model\BizGoodsModel;
use app\model\PayPingModel;
use app\model\UserModel;
use app\model\MiniParsedown;
use app\model\BizTagRelationModel;
use app\model\PayQrcodeRecordModel;
use app\model\BizAdminModel;

class BizController {
    
    /**
     * 列表
     * @param \support\Request $request
     * @return mixed
     */
    public function index(Request $request){
        try {
            $page = $request->get('current', 1);
            $pageSize = $request->get('pageSize', 10);
            $sortType = $request->get('type', 'recommend');
            $range = $request->get('range', 'recommend');

            $query = BizModel::query();

            // 根据排序类型设置排序规则
            switch($sortType) {
                case 'distance':
                    // 距离排序（这里可以根据用户位置计算，暂时按ID排序）
                    $query->orderBy('id', 'asc');
                    break;
                case 'rating':
                    // 好评排序（按评分排序）
                    $query->orderBy('star', 'desc');
                    break;
                case 'star':
                    // 星级排序（按星级排序）
                    $query->orderBy('star', 'desc');
                    break;
                default:
                    $query->orderBy('sort_by', 'desc');
                    break;
            }

            if($range == 'recommend'){

            }else if($range == 'topic'){
                $tagId = 2;
                // 通过标签关联表筛选商家
                $bizIds = BizTagRelationModel::where('tag_id', $tagId)->pluck('biz_id')->toArray();
                if (!empty($bizIds)) {
                    $query->whereIn('id', $bizIds);
                } else {
                    // 如果没有找到关联的商家，返回空结果
                    $query->where('id', 0);
                }

            }else if($range == 'birthday'){
                $tagId = 1;
                // 通过标签关联表筛选商家
                $bizIds = BizTagRelationModel::where('tag_id', $tagId)->pluck('biz_id')->toArray();
                if (!empty($bizIds)) {
                    $query->whereIn('id', $bizIds);
                } else {
                    // 如果没有找到关联的商家，返回空结果
                    $query->where('id', 0);
                }
            }

            $data = $query->whereNull('deleted_at')->limit($pageSize)->offset(($page - 1) * $pageSize)->get();
            foreach($data as &$item){
                $item->image = Util::pathToUrl($item->image);
                $item['safe_biz_phone'] = $item->safeBizPhone();
                $item['avatar'] = Util::pathToUrl($item->avatar);


                $goodsList = BizGoodsModel::where('biz_id', $item->id)
                ->select([
                    'id',
                    'title',
                    'image',
                    'price',
                    'sellout_count'
                ])
                ->where('status','=',1)->orderBy('sellout_count','desc')->limit(3)->get();
                $goods_list = [];
                foreach($goodsList as $goods){
                    $goods->image = Util::pathToUrl($goods->image);
                    $goods->price = round($goods->price,2);
                    $goods_list[] = $goods;
                }
                $item['goods_list'] = $goods_list;

                $item['services'] = $item->formatService();
                $item['normal_discount_label'] = $item->normalDiscountLabel();
                $item['vip_discount_label'] = $item->vipDiscountLabel();
            }
            
            return json([
                'code' => 1,
                'data' => $data,
                'total' => $query->count(),
                'msg' => '获取商家列表成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 搜索商家
     * @param \support\Request $request
     * @return mixed
     */
    public function search(Request $request){
        try {
            $page = $request->get('current', 1);
            $pageSize = $request->get('pageSize', 10);
            $keyword = $request->get('keyword', '');

            if (empty($keyword)) {
                throw new \Exception('搜索关键词不能为空');
            }

            $query = BizModel::query();
            $query->whereNull('deleted_at')
                  ->where(function($q) use ($keyword) {
                      $q->where('name', 'like', '%' . $keyword . '%')
                        ->orWhere('biz_phone', 'like', '%' . $keyword . '%');
                  });

            $total = $query->count();
            $data = $query->orderBy('sort_by', 'desc')
                         ->limit($pageSize)
                         ->offset(($page - 1) * $pageSize)
                         ->get();

            foreach($data as $item){
                $item->image = Util::pathToUrl($item->image);
                $item['safe_biz_phone'] = $item->safeBizPhone();

                $goodsList = BizGoodsModel::where('biz_id', $item->id)
                ->select([
                    'id',
                    'title',
                    'image',
                    'price',
                ])
                ->where('status','=',1)->get();
                $goods_list = [];
                foreach($goodsList as $goods){
                    $goods->image = Util::pathToUrl($goods->image);
                    $goods->price = round($goods->price,2);
                    $goods_list[] = $goods;
                }
                $item['goods_list'] = $goods_list;

                $item['services'] = $item->formatService();
            }

            return json([
                'code' => 1,
                'data' => $data,
                'total' => $total,
                'msg' => '搜索成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 详情
     * @param \support\Request $request
     * @return mixed
     */
    public function detail(Request $request){
        $id = $request->get('id');
        $data = BizModel::where('id', $id)->first();

        $data['image'] = Util::pathToUrl($data['image']);
        $data['safe_biz_phone'] = $data->safeBizPhone();
        $data['tags'] = $data->doTags();
        $data['special_note'] = empty($data['special_note']) ? false : nl2br($data['special_note']);

        $services = $data->formatService();
        $data['services'] = array_slice($services, 0, 3);
        $data['services_all'] = $services;
        
        $data['avatar'] = Util::pathToUrl($data['avatar']);
        $data['pos'] = $data->doPos();
        $data['desc'] = empty($data['desc']) ? '' : MiniParsedown::instance()->text($data['desc']);
        $data['have_desc'] = !empty($data['desc']);
        $data['comment_total'] = PayPingModel::where('biz_id', $id)->count();

        $data['hours'] = $data->formatBusinessHours();

        if($data->multi_biz_id > 0 ){
            $data['multi_biz_total'] = BizModel::where('multi_biz_id', '=',$data['multi_biz_id'])->count();
            $data['multi_bizs'] = BizModel::where('multi_biz_id', '=',$data['multi_biz_id'])->get();
        }else{
            $data['multi_bizs'] = [];
            $data['multi_biz_total'] = 0;
        }

        $data['vip_discount_label'] = $data->vipDiscountLabel();
        $data['normal_discount_label'] = $data->normalDiscountLabel();
        

        return json([
            'code' => 1,
            'data' => $data,
        ]);
    }

    public function pings(Request $request){
        $id = $request->get('id');
        $data = PayPingModel::where('biz_id', '=',$id)
            ->orderBy('id', 'desc')->limit(10)->get();

        foreach($data as $item){
            $item['images'] = $item->doImages();

            $item['user'] = UserModel::userCache($item->user_id);
        }

        return json([
            'code' => 1,
            'data' => $data,
        ]);
    }

    public function payQrcodeRecord(Request $request){
        try{
            $user = $request->userLogin;
            $id = $request->post('id');

            $admin = BizAdminModel::where('user_id', $user->id)->first();
            if(!$admin){
                throw new \Exception('当前用户无权操作');
            }

            $biz = BizModel::where('id', $admin->biz_id)->first();
            if(!$biz){
                throw new \Exception('商家不存在');
            }

            $biz->image = Util::pathToUrl($biz->image);
            $biz->avatar = Util::pathToUrl($biz->avatar);

            $data = PayQrcodeRecordModel::where('id', $id)->first();
            if(!$data){
                throw new \Exception('支付码记录不存在');
            }

            $data->biz_id = $biz->id;
            $data->save();

            $customer = UserModel::where('id', $data->user_id)->first();
            if(!$customer){
                throw new \Exception('顾客不存在');
            }

            $customer->headimg = Util::pathToUrl($customer->headimg);
            $customer->phone = $customer->safePhone();

            return json([
                'code' => 1,
                'data' => [
                    'biz' => $biz,
                    'customer' => $customer,
                ],
            ]);
        }catch(\Exception $e){
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
        
    }

    /**
     * 获取商家管理员列表
     * @param \support\Request $request
     * @return mixed
     */
    public function getAdmins(Request $request){
        try {
            $user = $request->userLogin;
            if (!$user) {
                throw new \Exception('用户未登录');
            }

            // 检查当前用户是否为商家管理员
            $currentAdmin = BizAdminModel::where('user_id', $user->id)->first();
            if (!$currentAdmin) {
                throw new \Exception('当前用户不是商家管理员');
            }

            // 获取该商家的所有管理员
            $admins = BizAdminModel::where('biz_id', $currentAdmin->biz_id)
                ->with('user')
                ->orderBy('created_at', 'desc')
                ->get();

            $adminList = [];
            foreach ($admins as $admin) {
                $userInfo = UserModel::where('id', $admin->user_id)->first();
                if ($userInfo) {
                    $adminList[] = [
                        'id' => $admin->id,
                        'user_id' => $admin->user_id,
                        'role' => $admin->role,
                        'status' => $admin->status,
                        'created_at' => date('Y-m-d H:i:s', $admin->created_at),
                        'user' => [
                            'id' => $userInfo->id,
                            'nickname' => $userInfo->nickname,
                            'phone' => $userInfo->safePhone(),
                            'headimg' => Util::pathToUrl($userInfo->headimg)
                        ]
                    ];
                }
            }

            return json([
                'code' => 1,
                'data' => $adminList,
                'msg' => '获取管理员列表成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 添加商家管理员
     * @param \support\Request $request
     * @return mixed
     */
    public function addAdmin(Request $request){
        try {
            $user = $request->userLogin;
            if (!$user) {
                throw new \Exception('用户未登录');
            }

            $input = $request->post('data');

            $phone = $input['phone'];
            $role = $input['role'];

            if (empty($phone)) {
                throw new \Exception('手机号不能为空');
            }

            if (!in_array($role, ['super', 'normal'])) {
                throw new \Exception('角色参数错误');
            }

            // 检查当前用户是否为超级管理员
            $currentAdmin = BizAdminModel::where('user_id', $user->id)->first();
            if (!$currentAdmin) {
                throw new \Exception('当前用户不是商家管理员');
            }

            if ($currentAdmin->role !== 'super') {
                throw new \Exception('只有超级管理员可以添加其他管理员');
            }

            // 根据手机号查找用户
            $targetUser = UserModel::where('phone', $phone)->first();
            if (!$targetUser) {
                throw new \Exception('该手机号用户不存在');
            }

            // 检查该用户是否已经是该商家的管理员
            $existingAdmin = BizAdminModel::where('biz_id', $currentAdmin->biz_id)
                ->where('user_id', $targetUser->id)
                ->first();
            if ($existingAdmin) {
                throw new \Exception('该用户已经是商家管理员');
            }

            // 创建新的管理员记录
            $newAdmin = new BizAdminModel();
            $newAdmin->biz_id = $currentAdmin->biz_id;
            $newAdmin->user_id = $targetUser->id;
            $newAdmin->role = $role;
            $newAdmin->status = 1;
            $newAdmin->created_at = time();
            $newAdmin->updated_at = time();
            $newAdmin->save();

            return json([
                'code' => 1,
                'data' => null,
                'msg' => '添加管理员成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 删除商家管理员
     * @param \support\Request $request
     * @return mixed
     */
    public function removeAdmin(Request $request){
        try {
            $user = $request->userLogin;
            if (!$user) {
                throw new \Exception('用户未登录');
            }

            $input = $request->post('data');
            if (empty($input['admin_id'])) {
                throw new \Exception('管理员ID不能为空');
            }

            // 检查当前用户是否为超级管理员
            $currentAdmin = BizAdminModel::where('user_id', $user->id)->first();
            if (!$currentAdmin) {
                throw new \Exception('当前用户不是商家管理员');
            }

            if ($currentAdmin->role !== 'super') {
                throw new \Exception('只有超级管理员可以删除其他管理员');
            }

            // 查找要删除的管理员
            $targetAdmin = BizAdminModel::where('id', $input['admin_id'])
                ->where('biz_id', $currentAdmin->biz_id)
                ->first();
            if (!$targetAdmin) {
                throw new \Exception('管理员不存在');
            }

            // 不能删除自己
            if ($targetAdmin->user_id == $user->id) {
                throw new \Exception('不能删除自己');
            }

            // 删除管理员
            $targetAdmin->delete();

            return json([
                'code' => 1,
                'data' => null,
                'msg' => '删除管理员成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }

    /**
     * 获取当前用户的管理员信息
     * @param \support\Request $request
     * @return mixed
     */
    public function getCurrentAdminInfo(Request $request){
        try {
            $user = $request->userLogin;
            if (!$user) {
                throw new \Exception('用户未登录');
            }

            $admin = BizAdminModel::where('user_id', $user->id)->first();
            if (!$admin) {
                throw new \Exception('当前用户不是商家管理员');
            }

            $biz = BizModel::where('id', $admin->biz_id)->first();
            if (!$biz) {
                throw new \Exception('商家不存在');
            }

            return json([
                'code' => 1,
                'data' => [
                    'admin' => [
                        'id' => $admin->id,
                        'role' => $admin->role,
                        'status' => $admin->status,
                        'created_at' => $admin->created_at
                    ],
                    'biz' => [
                        'id' => $biz->id,
                        'name' => $biz->name,
                        'image' => Util::pathToUrl($biz->image)
                    ]
                ],
                'msg' => '获取管理员信息成功'
            ]);
        } catch (\Exception $e) {
            return json([
                'code' => 0,
                'data' => null,
                'msg' => $e->getMessage()
            ]);
        }
    }
}
